<?php

namespace app\admin\controller\community\project;

use app\common\controller\Backend;
use think\Db;

/**
 * 项目课程预置管理
 *
 * @icon fa fa-calendar
 */
class Setcourse extends Backend
{
    protected $model = null;
    protected $noNeedRight = ['lists2'];
    protected $noNeedLogin=['lists2'];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\community\project\Setcourse;
            // 加载语言包
        //$this->assign('lang', $this->request->lang());
    }

    /**
     * 查看
     */
    public function index()
    {
        $user=$this->auth->getUserInfo();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        
        // 获取项目列表传递给视图
        $schoolName = $this->auth->school_name;
        $projects = Db::name('fa_community_publicwelfare p')
            ->join('fa_community c', 'p.community_id = c.id') // 关联 fa_community 表
            ->join('fa_cityarea a', 'c.district_id = a.id') // 关联 fa_cityarea 表
            ->where('p.community_id', $user['community_id'])
            ->order('p.createtime DESC')
            ->field('DISTINCT p.project_name, p.id publicwelfare_id, a.name as district_name') 
            ->select();
        $this->view->assign('projects', $projects);
        
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            // 使用别名来避免表名冲突
            $tableName = $this->model->getQuery()->getTable();
            // 定义搜索字段和排序字段
            $searchFields = ['p.school_name', 'p.project_name', 'p.course_name', 'c.name'];
            $sortFields = ['id' => 'p.id', 'school_name' => 'p.school_name', 'project_name' => 'p.project_name', 'course_name' => 'p.course_name', 'createtime' => 'p.createtime', 'updatetime' => 'p.updatetime'];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams($sortFields, $searchFields);

            $list = $this->model
                ->alias('p')
                ->join('fa_community c', 'p.community_id = c.id', 'LEFT')
                ->join('fa_cityarea a', 'c.district_id = a.id','LEFT');
            
            // 搜索条件已由 filter/op 参数和 search 参数处理
            
            // 处理快速搜索
            $search = $this->request->get('search');
            if (!empty($search)) {
                // 快捷搜索框直接搜索多个字段
                $list->where(function ($query) use ($search) {
                    $query->where('p.project_name', 'like', '%' . $search . '%')
                          ->whereOr('p.school_name', 'like', '%' . $search . '%')
                          ->whereOr('p.course_name', 'like', '%' . $search . '%')
                          ->whereOr('c.name', 'like', '%' . $search . '%');
                });
            }
            
            // 处理高级搜索参数
            $filter = $this->request->get('filter', '');
            $op = $this->request->get('op', '');
            
            if ($filter && $op) {
                $filter = (array)json_decode($filter, true);
                $op = (array)json_decode($op, true);
                foreach ($filter as $key => $val) {
                    if ($val) {
                        $operator = isset($op[$key]) ? $op[$key] : 'like';
                        if ($operator == 'like') {
                            $list->where($key, 'like', "%{$val}%");
                        } else {
                            $list->where($key, $operator, $val);
                        }
                    }
                }
            }
            
            // 处理项目筛选
            $publicwelfare_id = $this->request->get('publicwelfare_id', 0);
            \think\Log::info('Received publicwelfare_id: ' . $publicwelfare_id);
            
            if ($publicwelfare_id && $publicwelfare_id !== 'all' && $publicwelfare_id > 0) {
                $list->where('p.publicwelfare_id', $publicwelfare_id);
                \think\Log::info('Applied project filter for ID: ' . $publicwelfare_id);
            } else {
                \think\Log::info('No project filter applied - showing all projects');
            }
            // 当 publicwelfare_id 为 'all' 或 0 时，不添加过滤条件，显示所有数据
            
            if ($user['group_id'] == 8) {
                $list =$list->where('p.community_id', '=', $user['community_id']);
            }

            $list =$list->field('
        p.*,
        c.name as community_name,
        a.name as district_name
    ');
            
            // 添加排序条件
            if ($sort) {
                // 处理排序字段，确保使用正确的表名前缀
                switch ($sort) {
                    case 'id':
                        $list->order('p.id', $order);
                        break;
                    case 'school_name':
                        $list->order('p.school_name', $order);
                        break;
                    case 'project_name':
                        $list->order('p.project_name', $order);
                        break;
                    case 'course_name':
                        $list->order('p.course_name', $order);
                        break;
                    case 'district_name':
                        $list->order('a.name', $order);
                        break;
                    case 'community_name':
                        $list->order('c.name', $order);
                        break;
                    case 'createtime':
                        $list->order('p.createtime', $order);
                        break;
                    case 'updatetime':
                        $list->order('p.updatetime', $order);
                        break;
                    default:
                        $list->order('p.id', $order);
                }
            } else {
                $list->order('p.id', 'desc');
            }
            
            // 执行查询并打印SQL
            $list->fetchSql(false);
            $debug = Db::getLastSql();
            trace("SQL语句: " . $debug, 'debug');
            
            // 执行实际查询
            $list = $list->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $user=$this->auth->getUserInfo();
        
        // 获取从列表页传递过来的项目 ID
        $selected_project = $this->request->param('publicwelfare_id', 0);
        
        // 转换为整数确保比较正确
        $selected_project = intval($selected_project);
        
        // 将项目 ID 存入会话，以便在表单提交后仍能访问
        if (!empty($selected_project)) {
            $_SESSION['think']['admin']['publicwelfare_id'] = $selected_project;
        } elseif (isset($_SESSION['think']['admin']['publicwelfare_id'])) {
            $selected_project = intval($_SESSION['think']['admin']['publicwelfare_id']);
        }
        
        // 调试信息
        trace("Selected project ID: " . $selected_project, 'debug');
        
        // 将项目 ID 传递给视图
        $this->view->assign('selected_project', $selected_project);
        
        // 在页面上显示调试信息
        $this->view->assign('debug_info', [
            'selected_project' => $selected_project,
            'request_method' => $this->request->method(),
            'get_params' => $this->request->get(),
            'post_params' => $this->request->post(),
            'session_project' => isset($_SESSION['think']['admin']['publicwelfare_id']) ? $_SESSION['think']['admin']['publicwelfare_id'] : 'not set'
        ]);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                //判断是否有已经有课程名称是相同的
                $hasSameCourse = $this->model->where("publicwelfare_id","=",$params['publicwelfare_id'])->where('course_name', $params['course_name'])->where('community_id', $user['community_id'])->find();
                if ($hasSameCourse) {
                    $this->error(__('课程名称重复，请重新输入'));
                }
                // 如果是社区管理员，自动设置社区ID
                if ($this->auth->group_id == 8) {
                    $params['community_id'] = $user['community_id'];
                    $params['school_name'] = $this->auth->school_name;
                }else{
                    $params['school_name'] = Db::name('fa_community')->where('id', $user['community_id'])->value('name');
                    $params['community_id'] = $user['community_id'];
                }
                $params['project_name'] = Db::name('fa_community_publicwelfare')->where('id', $params['publicwelfare_id'])->value('project_name');
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取该学校的所有项目
        $schoolName = $this->auth->school_name;
        $user = $this->auth->getUserInfo();
        $projects = Db::name('fa_community_publicwelfare p')
            ->join('fa_community c', 'p.community_id = c.id',  'LEFT') // 关联 fa_community 表
            ->join('fa_cityarea a', 'c.district_id = a.id','LEFT') // 关联 fa_cityarea 表
            ->where('p.community_id', $user['community_id'])
            ->order('p.createtime DESC')
            ->field('DISTINCT p.project_name,p.id publicwelfare_id, a.name as district_name') // 添加 district_name
            ->select();
        $this->view->assign('projects', $projects);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
            $user = $this->auth->getUserInfo();
            
            // 如果是社区管理员，自动设置社区ID和学校名称
            if ($this->auth->group_id == 8) {
                $params['community_id'] = $user['community_id'];
                $params['school_name'] = $this->auth->school_name ?: $row['school_name'];
            } else {
                // 否则从社区表中获取学校名称
                $params['school_name'] = Db::name('fa_community')->where('id', $user['community_id'])->value('name') ?: $row['school_name'];
                $params['community_id'] = $user['community_id'];
            }
            

            // 确保 school_name 不为空
            if (empty($params['school_name'])) {
                $params['school_name'] = $row['school_name'];
            }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->where(['id' => $ids])->update($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取该学校的所有项目
        $schoolName = $this->auth->school_name;
        $user = $this->auth->getUserInfo();
        $projects = Db::name('fa_community_publicwelfare p')
            ->join('fa_community c', 'p.community_id = c.id') // 关联 fa_community 表
            ->join('fa_cityarea a', 'c.district_id = a.id') // 关联 fa_cityarea 表
            ->where('p.community_id', $user['community_id'])
            ->order('p.createtime DESC')
            ->field('DISTINCT p.project_name,p.id publicwelfare_id, a.name as district_name') // 添加 district_name
            ->select();
        $this->view->assign('projects', $projects);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 获取课程列表
     */
    public function getCourses()
    {
        $projectName = $this->request->get('project_name');
        $schoolName = $this->auth->school_name;
        $user = $this->auth->getUserInfo();
        
        // 从课程表中获取该项目的所有课程
        $courses = Db::name('community_project_course')
            ->where('school_name', $schoolName)
            ->where('community_id', $user['community_id'])
            ->where('project_name', $projectName)
            ->field('DISTINCT course_name')
            ->select();
        
        return json(['code' => 1, 'data' => $courses]);
    }

    public function del( $ids= null){
        $ids = explode(',', $ids);
        $tableName = $this->model->getTable(); // 获取表名
        $result = Db::name($tableName)->where('id', 'in', $ids)->delete();
        if ($result) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
    }
    
    /**
     * 清除项目课程
     */
    public function clearProjectCourses()
    {
        $publicwelfare_id = $this->request->post('publicwelfare_id', 0);
        
        if (empty($publicwelfare_id)) {
            $this->error('请选择项目');
        }
        
        Db::startTrans();
        try {
            // 清除指定项目的课程数据
            $tableName = $this->model->getTable(); // 获取表名
            $result = Db::name($tableName)->where('publicwelfare_id', $publicwelfare_id)->delete();
            
            Db::commit();
            $this->success('项目课程已清除');
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }


    public function lists2(){
        $user = $this->auth->getUserInfo();

        if ($user['community_id']) {
            $m = db::name("fa_community_course_config");
            $m->where('community_id', $user['community_id']);
            $m->field('id,name');
            $list = $m->select();
            $total = db()->query("select count(1) as c from  fa_community_course_config where community_id='{$user['community_id']}'")[0];
            echo json_encode(array("list" => $list, "total" => $total['c']));
            return; // 添加return语句
        }
        echo json_encode(array("list" => [], "total" => 0));
    }
}